package com.example.websocket.websocket;

import com.alibaba.fastjson.JSONObject;
import com.example.websocket.websocket.entity.SpringUtils;
import com.example.websocket.websocket.entity.UserChat;
import com.example.websocket.websocket.mybatis.dao.UserChatDAO;
import com.example.websocket.websocket.service.UserChatService;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.Map;

public class WsServer extends WebSocketServer {

    @Autowired
    private UserChatService userChatService;

    public WsServer(int port){
        super(new InetSocketAddress(port));
    }
    
    public WsServer(InetSocketAddress address){
        super(address);
    }
    
    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        // ws连接的时候触发的代码，onOpen中我们不做任何操作
    }

    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        // 断开连接时候触发的代码
        userLeave(webSocket);
        System.out.println(s);
    }

    @Override
    public void onMessage(WebSocket webSocket, String s) {
        if (null != s && s.startsWith("online")){
            userJoin(webSocket, s.replace("online", ""));
            return;
        } else if (null != s && s.startsWith("offline")){
            userLeave(webSocket);
            return;
        } else {
            UserChat userChat = JSONObject.parseObject(s, UserChat.class);
            userChatService = SpringUtils.getBean(UserChatService.class);
            boolean num = userChatService.insert(userChat);
            if (num) {
                // 发送成功返回结果
                WsPool.sendMsgToUser(webSocket, "success");
                // 发送成功提醒接收人
                assert userChat != null;
                WebSocket sendWebSocket = WsPool.findWebSocket(userChat.getSendUserId().toString());
                WsPool.sendMsgToUser(sendWebSocket, "haveMsg");
                return;
            }
        }
        WsPool.sendMsgToUser(webSocket, "fail");
    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {
        System.out.println("on error");
        e.printStackTrace();
    }

    @Override
    public void onStart() {

    }

    private void userLeave(WebSocket conn){
        WsPool.removeUser(conn);
    }

    private void userJoin(WebSocket conn, String userName){
        WsPool.addUser(userName, conn);
    }



}
